 <?php 
	//require '../include/mysql_connect.php';
	include_once "../include/Functions.php";
	
	@set_time_limit(300);
	
	$data = file_get_contents("php://input");	
	$data = utf8_encode($data);
	$obj = json_decode($data, true);
	
	$exercise_id= $obj[0];
	$person_id = $obj[1];
	$cont = $obj[2];
	//echo $cont;
	
	$distance = 0;
	$km=1;
	$last_alt;
	$current_alt;
	$ascent_km=0;
	$ascent_total=0;
	$descent_km=0;
	$descent_total=0;
	
	$sql = "";
	
	if($cont >= 1)
		$last_alt= $obj[3][0]['alt'];

	$rest = false;		
	for($i=0; $i < $cont; $i++){
		$rest= true;
		$sql= "UPDATE data_exerc 
				SET alt = {$obj[3][$i]['alt']} 
				WHERE (id_exerc = {$exercise_id}) 
				AND (d_time = {$obj[3][$i]['d_time']}) 
				AND (id_person = {$person_id}); ";
			mysql_query($sql) or die("Erro ao atualizar dados! ".mysql_error());
		
		$current_alt = $obj[3][$i]['alt'];
		//Ascent
		if( $current_alt > $last_alt){
			$ascent_km+= $current_alt - $last_alt;
			$ascent_total+= $current_alt - $last_alt;
		}
		else{
			$descent_km+= $last_alt - $current_alt;
			$descent_total+= $last_alt - $current_alt;
		}
		
		$last_alt= $current_alt;
		$distance= $obj[3][$i]['distance'];
		if( $distance >= $km){
			$rest= false;
			$sql= "UPDATE estatistics 
					SET ascent = {$ascent_km}, 
						descent = {$descent_km} 
					WHERE (id_exerc = {$exercise_id}) 
					AND (km = {$km}) 
					AND (id_person = {$person_id}); ";
				echo $sql;
				mysql_query($sql) or die("Erro ao atualizar dados! ".mysql_error());			
				
				$ascent_km=0;
				$descent_km=0;
		
				$km++;
		}
	}

	//Update last km
	if( $rest){
		$km--;
		/*$sql = "SELECT km 
				FROM estatistics 
				WHERE km > {$km} 
					AND (id_exerc = {$exercise_id}) 
					AND (id_person = {$person_id}); ";
		echo $sql;
		$km = Functions::getValue($sql);*/
		$sql= "UPDATE estatistics 
					SET ascent = {$ascent_km}, 
						descent = {$descent_km} 
					WHERE (id_exerc = {$exercise_id}) 
					AND (km > {$km}) 
					AND (id_person = {$person_id}); ";
		//echo $sql;
		mysql_query($sql);			
	}
	
	$elevation_gain= $ascent_total;//- $descent_total;
	$sql= "UPDATE exercise
			SET elevation_gain = {$elevation_gain}, exported = TRUE 
			WHERE (id = {$exercise_id})  
			AND (id_person = {$person_id}); ";
		echo $sql;
		mysql_query($sql) or die("Erro ao atualizar dados! ".mysql_error());	
	
	
	//var_dump(json_decode($data, true));
?>
